/*
 *  Copyright 2011-2012 Redia A/S
 * 
 *  This file is part of Redias Android Utilities.
 *
 *  Redias Android Utilities is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redias Android Utilities is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redias Android Utilities.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.lib.utils;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import dk.redia.lib.log.Log;

public class ImageUtils {
	
	public static final int MODE_CROP = 1;
	public static final int MODE_BOUNDING_BOX = 2;
	private static final String logTag = "ImageUtils";
	
	public static Bitmap resize(Bitmap src, int targetWidth, int targetHeight, int mode) {
		Matrix resizeMatrix = new Matrix();
		float scaleX = ((float)targetWidth)/((float)src.getWidth());
		float scaleY = ((float)targetHeight)/((float)src.getHeight());
		float scale = Math.max(scaleX, scaleY);
		resizeMatrix.postScale(scale, scale);
		Bitmap scaledSrc = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), resizeMatrix, false);
		Log.d(logTag, "Created scaled (but probably too big) bitmap of size " + scaledSrc.getWidth() + "x" + scaledSrc.getHeight());
		if (scaledSrc.getWidth()>targetWidth) {
			int extraPixelCount = scaledSrc.getWidth()-targetWidth;
			Log.d(logTag, "Need to crop " + extraPixelCount + " pixes horizontally");
			scaledSrc = Bitmap.createBitmap(scaledSrc, extraPixelCount/2, 0 , targetWidth, scaledSrc.getHeight(), null, false);
		}
		if (scaledSrc.getHeight()>targetHeight) {
			int extraPixelCount = scaledSrc.getHeight()-targetHeight;
			Log.d(logTag, "Need to crop " + extraPixelCount + " pixels vertically");
			scaledSrc = Bitmap.createBitmap(scaledSrc, 0, extraPixelCount/2, scaledSrc.getWidth(), targetHeight, null, false);
		}
		System.gc(); // Probably a good time to do some garbage collection
		return scaledSrc;
	}
}
